/**
 * 文档作者: wj
 * 创建时间：2018年05月12日
 * 修改时间：2018年05月12日
 * 描述信息：微商城首页
 */

import React, { Component } from 'react';
import './home.scss';
import ProductList from '../components/product-list/product-list';
import Search from '../components/search/search';
import util from '../../util/util';
import userModel from '../api/user.model';

class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      userInfo: null,
      productListData: null,
      hasList: false
    };
    this.userModel = userModel;
    this.saveList = [];
    this.orderScroll = this.orderScroll.bind(this);
    this.page = 1;
  }

  componentDidMount() {
    util.setTitle('微商城');
    util.wxShare();
    if (!userModel.keep) {
      // 第一次加载
      this.userModel.init('home').then(res => {
        this.setState({
          userInfo: res
        })
        return res;
      }).then(() => {
        this.getListByCond().then(res => {
          this.setState({
            productListData: res
          })
        });
      }).catch(() => {
        this.getListByCond().then(res => {
          this.setState({
            productListData: res
          })
        });
      })
    } else {
      this.getListByCond().then(res => {
        this.setState({
          productListData: res
        })
      });
    }
    window.addEventListener('scroll', this.orderScroll);
  }

  render() {
    return userModel.svcRegWithWx ? <div className='home-page'>
      <Search self={this} searchResult={this.getListByCond.bind(this)}></Search>
      <ProductList onProductList={this.onProductList.bind(this)} data={this.state.productListData}></ProductList>
      {this.state.hasList ? '' : <p className='flex-center'>
      <img className='loading' 
      src={require('../../assets/img/loading.png')}
      alt='loading'/>正在加载...</p>}
    </div> : '';
  }

  componentWillUnmount() {
    window.removeEventListener('scroll', this.orderScroll);
  }

  /** http获取列表，该方法传给search组件 */
  getListByCond(target = '') {
    return new Promise(resolve => {
      if (target === '' && this.saveList.length === 0) {
        this.getList(target).then(res => {
          resolve(res);
          if (target === '') {
            this.saveList = res;
          }
        })
      } else {
          resolve(this.saveList);
      }
    })
  }
  
  /**
   * 单击列表
   * @param {Object} node 单击的节点数据
   */
  onProductList(node) {
    this.props.history.push(`/details?sku=${node.sku}`);
  }

  /**
   * 滚动事件
   */
  orderScroll() {
    if (!this.state.hasList) {
      const scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
      const windowHeight = document.body.scrollHeight;
      const scrollHeight = document.documentElement.clientHeight || document.body.clientHeight;
      if ((scrollTop + scrollHeight) === windowHeight) {
        this.getList().then(res => {
          if (res.length === 0) {
            this.setState({
              hasList: true
            });
          } else {
            this.setState({
              productListData: this.state.productListData.concat(res)
            })
          }
        })
      }
    }
  }

  /** 获取列表 */
  getList(target = '') {
    return new Promise(resolve => {
      window.$http.post(`${window.$apiUrl}/svcShop/svcLoadSkuListByCond`, {
        uid: userModel.svcRegWithWx.uid,
        apptoken: userModel.svcRegWithWx.apptoken,
        "qword": target,
        "page": this.page++
      }).then(res => {
        resolve(res.data.info.data);
      })
    })
  }
}

export default Home;
